package com.study.base.io.nio.mainsubreactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by tan on 2017/7/18.
 */
public class MainReactor implements Runnable {

	private Selector selector;
	private ServerSocketChannel serverSocket;

	public MainReactor(int port) throws IOException {
		selector = Selector.open();
		serverSocket = ServerSocketChannel.open();
		serverSocket.socket().bind(new InetSocketAddress(port));
		serverSocket.configureBlocking(false);

		SelectionKey key = serverSocket.register(selector, SelectionKey.OP_ACCEPT);
		key.attach(new Acceptor(serverSocket));
	}

	@Override
	public void run() {

		try {
			while (!Thread.interrupted()) {
				selector.select();
				Set<SelectionKey> keySet = selector.selectedKeys();
				Iterator it = keySet.iterator();
				while (it.hasNext()) {
					//当key.isAcceptable()==true时，key是serverSocket的key
					//当key.isReadable()==true时，key是客户端的key
					dispatch((SelectionKey) it.next());
				}

				keySet.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void dispatch(SelectionKey key) {

		Runnable r = (Runnable) (key.attachment());
		if (r != null) {
			r.run();
		}
	}

}
